﻿#region Copyright
// Copyright (c) 2011-2012 RaisingForce Team (Alikin Sergey)
//
// Permission is hereby granted, free of charge, to any person
// obtaining a copy of this software and associated documentation
// files (the "Software"), to deal in the Software without
// restriction, including without limitation the rights to use,
// copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the
// Software is furnished to do so, subject to the following
// conditions:
//
// The above copyright notice and this permission notice shall be
// included in all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
// EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
// OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
// NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
// HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
// WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
// FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
// OTHER DEALINGS IN THE SOFTWARE.
#endregion

using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Diagnostics.Contracts;
using System.Globalization;
using System.Linq;
using System.Windows.Controls;

namespace RaisingForce.Raise.Presentation.ViewModel.Specialized
{
    public abstract class SettingViewModel :
        ViewModelBase,
        IDataErrorInfo
    {
        #region Constructors

        protected SettingViewModel()
            : base()
        { }

        #endregion

        #region Private Declarations

        private static readonly IEnumerable<string> validatedProperties =
            Enumerable.Empty<string>();

        private string validationCachedProperty;

        private string validationCachedError;

        #endregion

        #region Protected Declarations

        protected virtual void invalidateValue()
        {
            // do nothing by default
        }

        protected virtual IEnumerable<string> ValidatedProperties
        {
            get
            {
                Contract.Ensures(Contract.Result<IEnumerable<string>>() != null);
                return validatedProperties;
            }
        }

        protected virtual string getValidationError(string propertyName)
        {
            return null;
        }

        protected void ClearValidationCache()
        {
            this.cachedIsValid = null;
            this.validationCachedProperty = null;
        }

        protected string GetValidationError(string propertyName)
        {
            if (!this.ValidatedProperties.Contains(propertyName))
            {
                return null;
            }
            if (this.validationCachedProperty == propertyName)
            {
                return this.validationCachedError;
            }
            this.validationCachedProperty = propertyName;
            this.validationCachedError = this.getValidationError(propertyName);
            return this.validationCachedError;
        }

        protected static string GetValidationRuleResult(
            ValidationRule rule,
            object value)
        {
            if (rule == null)
            {
                throw new ArgumentNullException("rule");
            }
            Contract.EndContractBlock();
            ValidationResult result =
                rule.Validate(value, CultureInfo.CurrentCulture);
            return result.IsValid ? null : (string)result.ErrorContent;
        }

        protected static bool ValidationRuleSucceeded(
            ValidationRule rule,
            object value)
        {
            Contract.Requires(rule != null);
            return GetValidationRuleResult(rule, value) == null;
        }

        protected static IEnumerable<string> GetValidatedProperties(
            IEnumerable<string> properties)
        {
            if (properties == null)
            {
                throw new ArgumentNullException("properties");
            }
            Contract.EndContractBlock();
            return properties.ToList().AsReadOnly();
        }

        #endregion

        #region IsValid Declarations

        public bool IsValid
        {
            get
            {
                if (this.cachedIsValid != null)
                {
                    return this.cachedIsValid.Value;
                }
                this.cachedIsValid = this.ValidatedProperties.All(
                    prop => this.GetValidationError(prop) == null);
                return this.cachedIsValid.Value;
            }
        }

        private bool? cachedIsValid; // = null

        #endregion

        #region ViewModel Properties

        public string LabelText
        {
            get { return this.DisplayName; }
            set { this.DisplayName = value; }
        }

        public override string DisplayName
        {
            get
            {
                return base.DisplayName;
            }
            protected set
            {
                if (base.DisplayName != value)
                {
                    base.DisplayName = value;
                    this.OnPropertyChanged("LabelText");
                }
            }
        }

        #endregion

        #region Public Methods

        public string GetFirstValidationError()
        {
            return this.ValidatedProperties
                .Select(prop => this.GetValidationError(prop))
                .FirstOrDefault(error => error != null);
        }

        public void InvalidateValue()
        {
            this.invalidateValue();
        }

        #endregion

        #region IDataErrorInfo Members

        public string Error
        {
            get { return null; }
        }

        public string this[string columnName]
        {
            get { return this.GetValidationError(columnName); }
        }

        #endregion
    }
}
